package org.steven.crm.app.api.processor.base;

import org.steven.crm.core.auth.UserSession;
import org.steven.crm.core.data.pagination.PageSearchResult;
import org.steven.crm.core.exception.ServiceException;
import org.steven.crm.core.service.BaseService;

import java.util.ArrayList;
import java.util.Map;

public abstract class BaseUserReadOnlyProcessor extends BaseProcessor {
	@Override
	public void startProcess() throws Exception {
	}
	
	@Override
	public void endProcess() throws Exception {
	}

	protected abstract BaseService getService();

	/**
	 * 标准读取接口
	 * @throws Exception
	 */
	public void readAction() throws Exception {
		Map<String, String> data = getService().read(getStringData("id"));

		securityCheck(data);

		setObjectData(data);
	}

	/**
	 * 标准读取接口
	 * @throws Exception
	 */
	public void readExtViewAction() throws Exception {
		Map<String, Object> data = getService().readExtView(getStringData("id"));

		securityCheck(data);

		setObjectData(data);
	}

	/**
	 * 标准查询接口
	 * @throws Exception
	 */
	public void searchAction() throws Exception {
		initPageInfo();
		String sort = getStringData("sort");
		Map<String, String> condition = getStringDatas();
		condition.put("userId", getLoginUserId());

		PageSearchResult result = getService().search(condition,
				"", new ArrayList<>(), sort,
				Integer.parseInt(getStringData("pageIndex")),
				Integer.parseInt(getStringData("pageNumber")));

		setObjectData(result);
	}

	public void searchExtViewAction() throws Exception {
		initPageInfo();
		String sort = getStringData("sort");
		Map<String, String> condition = getStringDatas();
		condition.put("userId", getLoginUserId());

		PageSearchResult result = getService().searchExtView(condition,
				"", new ArrayList<>(), sort,
				Integer.parseInt(getStringData("pageIndex")),
				Integer.parseInt(getStringData("pageNumber")));

		setObjectData(result);
	}

	protected void securityCheck(Map optionData) {
		if (optionData != null && !optionData.isEmpty()) {
			String userId = UserSession.get().get("id");
			if (!userId.equals(optionData.get("userId"))) {
				throw new ServiceException("没有权限操作该数据");
			}
		}
	}

	protected void securityCheckNotNull(Map optionData) {
		if (optionData != null && !optionData.isEmpty()) {
			String userId = UserSession.get().get("id");
			if (!userId.equals(optionData.get("userId"))) {
				throw new ServiceException("没有权限操作该数据");
			}
		} else {
			throw new ServiceException("数据不存在");
		}
	}
}